<template>
  <div class="project-management-container">
    <!-- 项目列表页面 -->
    <div v-if="currentView === 'list'" class="project-list-view"> 
      <div class="base-map-resource-content">
        <div class="query-content">
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline backend-form"
          >
            <el-form-item label="项目名称">
              <el-input 
                v-model="formInline.title" 
                placeholder="请输入项目名称"
                @change="onSubmit" 
              />
            </el-form-item>
            <el-form-item label="项目章节">
              <el-input 
                v-model="formInline.sectionTitle" 
                placeholder="请输入项目章节"
                @change="onSubmit" 
              />
            </el-form-item>
            <el-form-item label="项目状态">
              <el-select
                v-model="formInline.status"
                placeholder="请选择状态"
                @change="onSubmit"
                clearable
              >
                <el-option label="已发布" value="1" />
                <el-option label="未发布" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item class="backend-button">
              <el-button class="addButton" type="primary" @click="handleCreateProject">
                <i class="el-icon el-icon-plus"></i>
                新建项目
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="table">
          <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column align="center" label="序号" width="80">
              <template v-slot="{ $index }">
                {{ $index + 1 + formInline.pageSize * (formInline.pageIndex - 1) }}
              </template>
            </el-table-column>
            <el-table-column
              label="项目名称"
              prop="title"
              show-overflow-tooltip
            />
            <el-table-column
              label="项目章节"
              prop="sectionTitle"
              show-overflow-tooltip
            />
            <el-table-column
              label="项目描述"
              prop="description"
              show-overflow-tooltip
            />
            <el-table-column
              label="状态"
              prop="status"
              width="100"
            >
              <template v-slot="{ row }">
                <!-- <el-tag
                  :type="getStatusType(row.status)"
                  size="small"
                >
                  {{ getStatusText(row.status) }}
                </el-tag> -->
                <el-switch
                  v-model="row.status"
                  :active-value="'已发布'"
                  :inactive-value="'未发布'"
                  @change="handleStatusChange(row.pkid, row.status)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              prop="createdTime"
              show-overflow-tooltip
              width="150"
            />
            <el-table-column
              label="更新时间"
              prop="updatedTime"
              show-overflow-tooltip
              width="150"
            />
            <el-table-column label="操作" width="200">
              <template v-slot="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="handleEditProject(row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handlePreviewProject(row)"
                >
                  预览
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleCopyProject(row)"
                >
                  复制
                </el-button>
                <el-popconfirm
                  width="160px"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  icon-color="#626AEF"
                  @confirm="handleDeleteProject(row)"
                  :title="'确认删除项目 ' + row.title + ' 吗？'"
                >
                  <template v-slot:reference>
                    <el-button
                      type="text"
                      size="small"
                      class="del-btn"
                    >
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-pagination
          background
          layout="slot,prev, pager, next"
          :page-size="formInline.pageSize"
          :current-page="formInline.pageIndex"
          :total="total"
          @current-change="handlePageChange"
        >
          <template v-slot:default> 共{{ total }}个项目 </template>
        </el-pagination>
      </div>
    </div>

    <!-- 项目编辑器页面 -->
    <div v-else-if="currentView === 'editor'" class="project-editor-view">
      <ProjectEditor
        :project-id="currentProjectId"
        @back="handleBackToList"
        @save="handleProjectSave"
      />
    </div>

    <!-- 新建项目对话框 -->
    <el-dialog
      title="新建项目"
      :visible.sync="createDialogVisible"
      width="500px"
      @close="handleCreateDialogClose"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="title">
          <el-input v-model="createForm.title" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目章节" prop="sectionTitle">
          <el-input v-model="createForm.sectionTitle" placeholder="请输入项目章节" />
        </el-form-item>
        <el-form-item label="项目描述" prop="remark">
          <el-input
            v-model="createForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmCreate">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { Message } from 'element-ui'
import { getProjectList, addOrUpdateProject, deleteProject } from '@/api/screen-management/report-platform'
import ProjectEditor from './components/ProjectEditor.vue'
import type { ProjectQueryParams, ProjectItem, CreateProjectForm } from './interface'

// 视图状态
const currentView = ref<'list' | 'editor'>('list')
const currentProjectId = ref<string>('')

// 查询表单
const formInline = reactive<ProjectQueryParams>({
  pageIndex: 1,
  pageSize: 10,
  title: '',
  status: '',
  sectionTitle: '',
})

// 表格数据
const tableData = ref<ProjectItem[]>([])
const total = ref(0)

// 新建项目对话框
const createDialogVisible = ref(false)
const createFormRef = ref()
const createForm = reactive<CreateProjectForm>({
  title: '',
  sectionTitle: '',
  remark: '',
})

const createFormRules = {
  title: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  sectionTitle: [
    { required: true, message: '请输入项目章节', trigger: 'blur' }
  ]
}

// 获取项目列表
const getProjectData = async () => {
  try {
    const res = await getProjectList(formInline)
    if (res.success) {
      const { count, list } = res.data
      tableData.value = list || []
      total.value = count || 0
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 查询提交
const onSubmit = () => {
  formInline.pageIndex = 1
  getProjectData()
}

// 分页变化
const handlePageChange = (pageIndex: number) => {
  formInline.pageIndex = pageIndex
  getProjectData()
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    '0': '未发布',
    '1': '已发布'
  }
  return textMap[status] || '未知'
}

// 更新项目状态
const handleStatusChange = async (pkid: string, status: string) => {
  const res = await addOrUpdateProject({ pkid, status })
  if (res.success) {
    Message.success('项目状态更新成功')
    getProjectData()
  } else {
    Message.error(res.message || '项目状态更新失败')
  }
}

// 新建项目
const handleCreateProject = () => {
  createDialogVisible.value = true
  resetCreateForm()
}

// 确认新建项目
const handleConfirmCreate = async () => {
  try {
    await createFormRef.value?.validate()
    const res = await addOrUpdateProject(createForm)
    if (res.success) {
      Message.success('项目创建成功')
      createDialogVisible.value = false
      getProjectData()
    } else {
      Message.error(res.message || '项目创建失败')
    }
  } catch (error) {
    console.error('创建项目失败:', error)
  }
}

// 编辑项目
const handleEditProject = (row: ProjectItem) => {
  currentProjectId.value = row.pkid
  currentView.value = 'editor'
}

// 预览项目
const handlePreviewProject = (row: ProjectItem) => {
  // TODO: 实现预览功能
  Message.info('预览功能开发中...')
}

// 复制项目
const handleCopyProject = async (row: ProjectItem) => {
  try {
    const copyData = {
      title: `${row.title}_副本`,
      sectionTitle: row.sectionTitle,
    }
    const res = await addOrUpdateProject(copyData)
    if (res.success) {
      Message.success('项目复制成功')
      getProjectData()
    } else {
      Message.error(res.message || '项目复制失败')
    }
  } catch (error) {
    console.error('复制项目失败:', error)
    Message.error('项目复制失败')
  }
}

// 删除项目
const handleDeleteProject = async (row: ProjectItem) => {
  try {
    const params = {
      pkid: row.pkid
    }
    const res = await deleteProject(params)
    if (res.success) {
      Message.success('项目删除成功')
      getProjectData()
    } else {
      Message.error(res.message || '项目删除失败')
    }
  } catch (error) {
    console.error('删除项目失败:', error)
    Message.error('项目删除失败')
  }
}

// 返回列表
const handleBackToList = () => {
  currentView.value = 'list'
  currentProjectId.value = ''
  getProjectData() // 刷新列表
}

// 项目保存
const handleProjectSave = () => {
  Message.success('项目保存成功')
  getProjectData()
}

// 重置新建表单
const resetCreateForm = () => {
  createForm.title = ''
  createForm.sectionTitle = ''
  createForm.remark = ''
  nextTick(() => {
    createFormRef.value?.resetFields()
  })
}

// 关闭新建对话框
const handleCreateDialogClose = () => {
  resetCreateForm()
}

// 初始化
onMounted(() => {
  getProjectData()
})
</script>

<style lang="scss" scoped>
.project-management-container {
  width: 100%;
  height: calc(100% - 27px);
}

.project-list-view {
  width: 100%;
  height: 100%;
  // padding: 20px;
}

.base-map-resource-content {
  width: 100%;
  height: 100%;
  background-color: white;
  box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  display: flex;
  flex-direction: column;

  .query-content {
    padding: 20px;
    width: 100%;
    border-bottom: 1px solid #eeeff5;

    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 20px;

        .addButton {
          margin-left: 20px;
          margin-top: 14px;
          margin-bottom: 14px;
          width: 100px;
          min-height: 32px;
          //background: #28b1e4;
          border-radius: 2px;
          //border: none;
          padding: 0;
        }
      }
    }
  }

  .table {
    width: 100%;
    padding: 0 20px 20px 20px;
    overflow-y: auto;

    :deep(.el-table) {
      .el-table__header-wrapper {
        .el-table__header {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 500;
          }
        }
      }

      .el-table__row--striped {
        background: #fafafa;
      }
    }

    .del-btn {
      color: #f56c6c;
      margin-left: 10px;

      &:hover {
        color: #f78989;
      }
    }
  }

  :deep(.el-pagination) {
    margin-top: 20px;
    justify-content: end;
    margin-right: 18px;
    margin-bottom: 20px;
  }
}

.project-editor-view {
  width: 100%;
  height: 100%;
}

.dialog-footer {
  text-align: right;

  .el-button + .el-button {
    margin-left: 10px;
  }
}
</style>
